package com.yoda.youdianda.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yoda.youdianda.common.RC;
import com.yoda.youdianda.domain.SysMenu;
import com.yoda.youdianda.domain.SysRole;
import com.yoda.youdianda.dto.RoleDto;
import com.yoda.youdianda.dto.RoleInfoDto;
import com.yoda.youdianda.mapper.SysRoleMapper;
import com.yoda.youdianda.service.SysMenuService;
import com.yoda.youdianda.service.SysRoleMenuService;
import com.yoda.youdianda.service.SysRoleService;
import com.yoda.youdianda.util.Util;
import com.yoda.youdianda.vo.*;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;



/**
 * @author shawn
 * @date 2022年 11月 13日 8:58
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    @Autowired
    private SysRoleMapper roleMapper;


    @Autowired
    private SysRoleMenuService roleMenuService;


    @Autowired
    private SysMenuService menuService;



    @Override
    public SysRole getRoleById(String roleId) {
        return roleMapper.selectById(roleId);
    }

    /**
     * @param page     页面
     * @param pageSize 页面大小
     * @param name     名字
     * @return {@link PageResult}<{@link RolePageVo}>
     */
    @Override
    public PageResult<RolePageVo> selectByPage(Integer page, Integer pageSize, String name) {
        Page<SysRole> rolePage = new Page<>(page, pageSize);
        LambdaQueryWrapper<SysRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(Strings.isEmpty(name), SysRole::getName, name);
        wrapper.eq(SysRole::getDelFlag,0);
        wrapper.orderByDesc(SysRole::getCreateDate).orderByDesc(SysRole::getUpdateDate);
        roleMapper.selectPage(rolePage, wrapper);
        List<SysRole> roles = rolePage.getRecords();
        if (Objects.isNull(roles) || roles.size() == 0) {
            return new PageResult<>();
        }
        SimpleDateFormat format = new SimpleDateFormat(RC.GENERAL_DATE_FORMAT);
        List<RolePageVo> vos = new ArrayList<>();
        for (SysRole role : roles) {
            List<String> menuIds = roleMapper.getMenus(role.getId());
            RolePageVo vo = RolePageVo.init(role, menuIds, format);
            vos.add(vo);
        }
        return new PageResult<>(page, pageSize, (int) rolePage.getTotal(), vos);
    }

    /**
     * 得到所有
     *
     * @return {@link List}<{@link RoleVo}>
     */
    @Override
    public List<RoleVo> getAll() {
        LambdaQueryWrapper<SysRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysRole::getDelFlag,0);
        List<SysRole> roles = roleMapper.selectList(wrapper);
        SimpleDateFormat format = new SimpleDateFormat(RC.GENERAL_DATE_FORMAT);
        return roles.stream().map(r -> RoleVo.init(r, format)).collect(Collectors.toList());
    }

    @Override
    public List<SysRole> getRoleByIds(List<String> rolesId) {
        LambdaQueryWrapper<SysRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(!Objects.isNull(rolesId) && rolesId.size() > 0, SysRole::getId, rolesId);
        return roleMapper.selectList(wrapper);
    }

    @Override
    public RoleInfoVo getByUserId(String id) {
        SysRole role = roleMapper.selectById(id);
        SimpleDateFormat format = new SimpleDateFormat(RC.GENERAL_DATE_FORMAT);
        RoleInfoVo roleInfoVo = RoleInfoVo.init(role, format);
        //根据当前角色id,查询所有菜单id
       List<String> menuIds = roleMenuService.selectMenuByRoleId(id);
        //根据菜单id批量查询所有菜单
        List<SysMenu> menus = menuService.getAllByMenuIds(menuIds);
        //过滤出一级菜单
        SysMenu sysMenu = new SysMenu();
        sysMenu.setId(0);
        List<MenuDetailVo> vos = Util.getStructuredDirectory(menus, sysMenu);
        roleInfoVo.setAuthList(vos);
        return roleInfoVo;
    }


    @Override
    public boolean deleteById(String id) {

        SysRole role = new SysRole();
        role.setId(id);
        role.setDelFlag("1");
        int count = roleMapper.updateById(role);
        return count > 0;
    }

    @Transactional
    @Override
    public boolean insert(RoleDto dto) {
        SysRole sysRole = RoleDto.init(dto);
        int count1 = roleMapper.insert(sysRole);
        List<Integer> menuids = dto.getMenuids();
        List<Integer> menuIds = new ArrayList<>();
        for (Integer menuId : menuids) {
            if (!menuIds.contains(menuId)) {
                menuIds.add(menuId);
            }
        }
        int count2 = roleMenuService.insertList(sysRole.getId(), menuIds);

        return count1 > 0 && count2>0;
    }
    @Transactional
    @Override
    public boolean updateById(RoleInfoDto dto) throws ParseException {
        SysRole sysRole = RoleInfoDto.init(dto);
        roleMapper.updateById(sysRole);
        //根据id删除所有菜单关联表
        roleMenuService.deleteByRoleId(sysRole.getId());
        //批量新增
        roleMenuService.insertList(dto.getId(),dto.getMenuids());
        return true;
    }
}
